/*
 * @Author: 刘岩 15136056318@163.com
 * @Date: 2023-11-18 14:53:55
 * @LastEditors: LiuYan 15136056318@163.com
 * @LastEditTime: 2023-12-01 13:47:49
 * @FilePath: \react-template_pc\src\components\echart\index.tsx
 * @Description: 图表封装
 */
import * as echarts from 'echarts'
import { memo, useEffect, useRef } from 'react'
import type { EchartOptionsType } from './data'
import { pxToVh, pxToVw } from '@/utils'
/**
 * @description: 图表封装
 * @param {EchartOptionsType} param
 * @return {*}
 */
const Echart = ({
  option,
  width,
  height,
  isAnimation = false,
  unit = 'viewport',
}: EchartOptionsType): JSX.Element => {
  const dom = useRef(null)
  const initChart = () => {
    const chart = echarts.init(dom.current)
    chart.setOption(option)
    return chart
  }
  useEffect(() => {
    const myChart = initChart()
    const resize: any = () => {
      myChart.resize()
    }
    window.addEventListener('resize', resize)
    let currentIndex = -1
    let isAnimationTime: any = null
    if (isAnimation && option.series?.length) {
      isAnimationTime = setInterval(function () {
        const endLength = option.series.length - 1
        const dataLen = option.series[endLength].data.length
        // 取消之前高亮的图形
        myChart.dispatchAction({
          type: 'downplay',
          seriesIndex: endLength,
          dataIndex: currentIndex,
        })
        currentIndex = (currentIndex + 1) % dataLen
        // 高亮当前图形
        myChart.dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          dataIndex: currentIndex,
        })
        // 显示 tooltip
        myChart.dispatchAction({
          type: 'showTip',
          seriesIndex: endLength,
          dataIndex: currentIndex,
        })
      }, 2000)
    }
    return () => {
      window.removeEventListener('resize', resize)
      if (isAnimationTime) clearInterval(isAnimationTime)
    }
  }, [option])
  return (
    <>
      <div
        ref={dom}
        style={{
          width:
            unit === 'viewport'
              ? width
                ? pxToVw(width)
                : '100%'
              : width
              ? width + 'px'
              : '100%',
          height:
            unit === 'viewport'
              ? height
                ? pxToVh(height)
                : '100%'
              : height
              ? height + 'px'
              : '100%',
          pointerEvents: 'auto',
        }}
      ></div>
    </>
  )
}
export default memo(Echart)
